#!/bin/sh
GRAPHITE_HOST=192.168.137.98
GRAPHITE_PORT=2003
INNER_IP=$(ip addr | (egrep ' (10\.|192\.168\.|172\.1[6-9]|172\.2[0-9]|172.3[0-1]\.)'; echo 127.0.0.1) | head -1 | awk -F'inet |/' '{print $2}')

command=$(which node)
if [ -z "$command" ]; then
    # install nodejs v0.12
    curl -sL https://deb.nodesource.com/setup_0.12 | sudo bash -
    sudo apt-get install -y nodejs
    # install hash ring
    npm install hashring
else
    echo "nodejs had installed."
fi

# add user
useradd statsd -mU

command=$(which git)
if [ -z "$command" ]; then
    # install git
    sudo apt-get install -y git
else
    echo "git had installed."
fi

home=/home/statsd
# install statsd
if [ -e $home/statsd ]; then
    echo "Statsd installed."
    exit
fi

git clone https://github.com/etsy/statsd.git $home/statsd
cp config-normal/ $home -R
mkdir $home/logs
chown statsd:statsd $home -R

# update config
pushd $home/config-normal
sed -i "s#%INNER_IP#$INNER_IP#g" *.js
sed -i "s#%GRAPHITE_HOST#$GRAPHITE_HOST#g" *.js
sed -i "s#%GRAPHITE_PORT#$GRAPHITE_PORT#g" *.js
popd

cp cluster_run_statsd.sh $home

echo "cd %home/"
echo "Usage: sh cluster_run_statsd.sh start normal"
